$(window).ready(function(){
	//JS_PlaceHolder();
	//循环生成上传图片的热点
	$(".icross2").each(uploadStepImg);	    //2013-03-11
	//添加主料，用量栏目
	$("#zhuliao").click(function(){
		var html = addCaiLiaoInfo();
		$(this).parent().before(html);
	})
	// 添加标签框的选中事件
	$("#cooktagInput").click(function(){
		$(this).find('input').focus();
	})
	//添加步骤图信息
	$("#addBuZhou").click(function(){
		//actionInputFile();
		var html = addBuZhou();
		
		$(this).parent().before(html);
		resortStepPosition();
		$(".icross2").each(uploadStepImgOne(obj));
	})
	//向上一步
	$(".ic_up").live('click', function(){
		var curStep = $(this).parents("div:first");
		var prevStep = curStep.prev();
	    var nextStep = curStep.next();
	    var curStepNum  = curStep.find('.umber').text();
	    if(curStepNum > 1)
	    {
	    	curStep.insertBefore(prevStep);
            resortStepPosition();
	    }
	})
	//向下一步
	$(".ic_dw").live('click', function(){
		var curStep = $(this).parents("div:first");
		var prevStep = curStep.prev();
	    var nextStep = curStep.next();
		if($('div.nsetp').index($(this).parents('div.nsetp')) != $('div.nsetp').size()-1)
		{
			curStep.insertAfter(nextStep);
	        resortStepPosition();
		}
	})
	//添加一步
	$(".ic_ad").live('click', function(){
		//actionInputFile();
		var html = addBuZhou();
		$(this).parents("div:first").after(html);
		resortStepPosition();
		 var obj = $(this).parents("div:first").next().children().children("div:first");
		uploadStepImgOne(obj);
	})
	//删除主料，辅料信息。
	$(".wrng").live("click", function(){
		$(this).parent().remove(); 
	})
	//删除详细步骤信息。
	$(".ic_close").live("click", function(){
		var steplen = ($(".nsetp").length);
		if(steplen > 1)
		{
			$(this).parents("div:first").remove();
			resortStepPosition();
		}
	})
	//显示，隐藏详细步骤信息操作。
	$(".nsetp").live("mouseover mouseout", function(event){
		if(event.type == "mouseout")
		{
			$(this).children('.sxgj').addClass("hidden");
		}else
		{
			$(this).children('.sxgj').removeClass("hidden");
		}
	})

	/**
	 * @desc: 上传菜谱成品图
	 * @return: json
	**/
	$.ajax_upload('#uploadCookImage', {
        action:'/uajax/upCookImageFile/cover',
        name:'uploadFile',
        data:{imgType:'coverImage'},
        dataType:'json',
        onSubmit: function (file, ext){
            ext = ext.toLowerCase();
	    $("#uploadCookImage").hide();
	    $('#iloading').show();
            if (!(ext && /^(jpg|png|jpeg|gif)$/i.test(ext)))
            {
                showErrorTips('图片格式不正确！');
                return false;
            }
        },
        onComplete : function(file, msg){
            var msg = eval('(' + msg + ')');
            if (msg.code == 'Success')
            {
            	$("#coverImageId").val(msg.id);
            	$("#coverImageUrl").val(msg.upload);
            	//$("#upCookImageCover").attr("src", msg.imgUrl);
            	//$("#upCookImageCover").show();
		$('#imgUploadNow').hide();
		$('#upCookImageCover').attr("src", msg.imgUrl);
		$('#imgUploadSucc').show();
		$("#uploadCookImage").show();
		$('#iloading').hide();
                //showerrorinfo('温馨提示', '上传成功！');
            }else
            {
            	//showerrorinfo('温馨提示', '上传失败！');
            }
        }
    })
})

/**
 * @desc: 添加主料/辅料信息栏目
 * @return: {String}
**/
function addCaiLiaoInfo()
{
	return '<div class="mct clearfix mbs"><span class="liao"><input type="text" class="liaoext fcbm" name="materials[str][]" value="" /></span><span class="liang"><input type="text" class="liangext fcbm" name="materials[int][]" value="" /></span><a href="javascript:void(0);" class="wrng"></a></div>';
}

/**
 * @desc: 添加详细步骤
 * @returns {String}
 * 2013-03-11
**/
function addBuZhou()
{
				var html = '<div class="nsetp mbm clearfix">'
					html +='<span class="umber rl3">1</span>'
					html +='<span class="bzmw mrs"><textarea name="setpInfos[]" class="steptext r3 fcbm"></textarea></span>'
					html +='<span class="tjbz">'
						html +='<div class="icross2">'
						html +='步骤图'
						html +='</div>'
						html +='<div class="iloading">'
						html +='正在上传…'
						html +='</div>'
					html +='</span>'
					html +='<span class="upimgsucc tjbz" style="display:none;">'
						    html +='<img src="" style="width:140px;display:none;"/><input type="hidden" name="setpImageIds[]" value="" /><input type="hidden" name="setpImages[]" value="" /><span class="reclose" style="display:none;"></span>'
					html +='</span>'
					html +='<span class="sxgj hidden">'
						   html += '<a href="javascript:void(0);" class="ic_up"></a>'
						    html +='<a href="javascript:void(0);" class="ic_dw"></a>'
						  html += ' <a href="javascript:void(0);" class="ic_ad"></a>'
						  html += ' <a href="javascript:void(0);" class="ic_close"></a>'
					html +='</span>'
				html +='</div>'
		return html;
}

/**
 * @desc: 添加主料/辅料，重新绑定上传图片信息
 * @return: null
**/
function actionInputFile()
{
	$(".tjbz").find("div").remove();
	$(".tjbz").html('<div class="setp_images" style="widht:140px; height:90px;"><img src="" style="width:140px; height:89px;display:none;"/></div>');
}

/**
 * @desc: 重新整理上传步骤排序
 * @return: number
**/
function resortStepPosition()
{
    var pos = 1;
    $("span.umber").each(function(){
        $(this).text(pos);
        pos++;
    })
}

/**
 * @desc: 绑定步骤页面
 * @return: {string}
**/
function uploadStepImg()
{
	var butStepImage = $(this);
    $.ajax_upload(butStepImage, {
        action: '/uajax/upCookImageFile/setp',
        name: 'uploadFile',
        data:{imgType:'setpImage'},
        dataType:'json',
        onSubmit: function (file, ext){
            ext = ext.toLowerCase();
		    butStepImage.hide();
		    butStepImage.parent().next().show();
            if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
            	showErrorTips('图片格式不正确！');
            	return false;
            }
        },
        onComplete : function(file, msg){
        	var msg = eval('(' + msg + ')');
            if (msg.code == 'Success')
            {
		butStepImage.parent().parent().hide();
		butStepImage.parent().parent().next().show();
		butStepImage.parent().parent().next().find("input[name='setpImageIds[]']").val(msg.id);
            	butStepImage.parent().parent().next().find("input[name='setpImages[]']").val(msg.upload);
		butStepImage.parent().parent().next().find("img").attr("src", msg.imgUrl).show();
		butStepImage.parent().parent().next().find("span[class='reclose']").show();
            }else
            {
            	showerrorinfo('温馨提示', '图片上传失败！');
            }
        }
    })
}

/**
 * @desc: 绑定步骤页面
 * @return: {string}
**/
function uploadStepImgOne(obj)
{
	var butStepImage = obj;
    $.ajax_upload(butStepImage, {
        action: '/uajax/upCookImageFile/setp',
        name: 'uploadFile',
        data:{imgType:'setpImage'},
        dataType:'json',
        onSubmit: function (file, ext){
            ext = ext.toLowerCase();
	    butStepImage.hide();
	    butStepImage.parent().next().show();
            if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))){
            	showErrorTips('图片格式不正确！');
            	return false;
            }
        },
        onComplete : function(file, msg){
        	var msg = eval('(' + msg + ')');
            if (msg.code == 'Success')
            {
		butStepImage.parent().parent().hide();
		butStepImage.parent().parent().next().show();
				butStepImage.parent().parent().next().find("input[name='setpImageIds[]']").val(msg.id);
            	butStepImage.parent().parent().next().find("input[name='setpImages[]']").val(msg.upload);
		butStepImage.parent().parent().next().find("img").attr("src", msg.imgUrl).show();
		butStepImage.parent().parent().next().find("span[class='reclose']").show();
            }else
            {
            	//showerrorinfo('温馨提示', '图片上传失败！');
            }
        }
    })
}




/**
 * @desc: 提交form表单信息
 * @return: boolean
**/
function uploadInfos()
{
    if($("#sinatoken").val() == 1 && $("#bye").val()==0 && $("#sinasns").attr("checked")){
       // notifySinaRebd();
    }
	var cookName = $("#cook_name").val();
	var cook_deal = $("#cook_deal").val();
	var cook_costtime = $("#costtime").val();
	var purview = $("#purview").val();
	//var setpInfo = $("input[name='setpImages[]']");
	if (cookName == '')
	{
		showErrorTips('没有填写菜谱名称！');
		backToTop();
		return false;
	}
	if(cookName.length > 30)
	{
		showErrorTips('菜谱名称字数过长！');
		backToTop();
		return false;
	}

	if(cook_deal == '' || cook_costtime == '')
	{
		var str = cook_deal == '' ? '请选择菜量！' : '请选择菜谱时间！';
		showErrorTips(str);
		backToTop();
		return false;
	}

	var coverImageUrl = $("#coverImageUrl").val();
	if(coverImageUrl == '')
	{
		showErrorTips('没有上传菜谱成品图！');
		backToTop();
		return false;
	}
	
	var stepleng = ($(".nsetp").length);
	var stepinfo = '';
	if(stepleng > 0)
	{
		for(var i = 0; i < stepleng; i++)
        {
			stepinfo += $(".nsetp").find("textarea").eq(i).val();
        }
		if(stepinfo == '')
		{
			showErrorTips('没有填写详细步骤');
			backToTop();
			return false;
		}
	}


	$("#uploadCaipuInfo").html("提交中...");
	$("#uploadCaipuInfo").attr('disabled',"true");
	$("#recipeform").submit();
}

$("#username").blur(function(){
	$("#nickname").html('');
	var username = $("#username").val();
	if(username != '')
	{
		$.ajax({
			type:"post",
			url:"/uajax/getUserinfo",
			data:"username="+username,
			dataType:"json",
			async: false,
			success: function(msg)
			{
				if(msg.data.info == 'OK')
				{
					$("#userid").val(msg.data.user_id);
					$("#nickname").html(msg.data.name);
				}else
				{
					$("#nickname").html("用户名错误！");
					$("#userid").val('');
				}
			}
		})
	}
})

//添加标签信息
function addcooktag(obj)
{
	obj	= $(obj);
	var diettags	= $('#cooktags').val();
	if(obj.hasClass('tied'))
	{
		if(diettags=='')
		{
			return flase;
		}
		var	search	= '';
		if(diettags.indexOf(obj.html())>0)
		{
			search	= ' '+obj.html();
		}
		else
		{
			search	= obj.html();
		}
		diettags	= diettags.replace(search,'');
		if(diettags!='')
		{
			diettags	= $.trim(diettags);
		}
		$('#cooktags').val(diettags);
		obj.removeClass('tied');
		$('.cooktag').each(function(k,v)
		{
			if($(v).html()==obj.html())
			{
				$(v).removeClass('tied');
			}
		})
		return true;
	}
	else
	{
		$('#cooktags').val(($.trim(diettags)=='多个标签用空格隔开'||$.trim(diettags)=='' ? '':$.trim(diettags)+' ')+obj.html());
		obj.addClass('tied');
		$('.cooktag').each(function(k,v)
		{
			if($(v).html()==obj.html())
			{
				$(v).addClass('tied');
			}
		})
	}
}
function showErrorTips(tips)
{
	$("#upwrongtips").html(tips).show();
}
function backToTop(num)
{
    var num = typeof num == 'undefined' ? 0 : num;
    if(num == 0)
    {
        t = $(document).scrollTop();
        num = t;
    }
    var t = $(document).scrollTop();
    $(document).scrollTop(t - num);
}

	$('#imgUploadSucc .tjbz mrl').mouseover(function(){
		$('#imgUploadSucc .zpclose').show();
	});
	$('#imgUploadSucc .tjbz mrl').mouseout(function(){
		$('#imgUploadSucc .zpclose').hide();
	});
	$('#imgUploadSucc .zpclose').live('click', function(){
		$('#imgUploadSucc').hide();
		$('#imgUploadNow').show();
		$('#img').val('');
		$('#imgUploadNow div[specid=uploadspecid]').attr('id','uploadDishImage');
		$("#tipInfos").show();
		$(".iload").hide();
		$('#coverImageUrl').val("");
		editUploadImg($('#imgUploadNow div[specid=uploadspecid]'));
	});

	$('.upimgsucc').live("mouseover",function(){
		$(this).find("span").show();
	});
	$('.upimgsucc').live("mouseout",function(){
		$(this).find("span").hide();
	});

	$('.reclose').live('click', function(){
		$(this).parent().find("img").val('');
		$(this).parent().hide();
		$(this).parent().prev().show();
		$(this).parent().prev().children().find("div[class='icross2 hover']").show();
		$(this).parent().prev().children().find("div[class='icross2']").show();
		$(this).parent().prev().find("div[class='iloading']").hide();
		$(this).parent().find("input[name='setpImages[]']").val("");
		//$(".icross2 hover").each(uploadStepImg);

	});